package com.tm.fiverole.ulits;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tm.fiverole.security.domain.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/***
 *
 * 新建一个JWT工具类
 * 用于生成和解析token
 */
public class JwtTokenUtil {


    private static final String SALT = "P#wZd1&q!E1o_.";

    private static final Long EXPIRATION_TIME = 30 * 60 * 1000L;

    /**
     * 生成token
     * @return
     */
    public static String generateToken(User user) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return Jwts.builder()
                    .setId(String.valueOf(user.getId()))
                    .claim("authorities", objectMapper.writeValueAsString(user.getAuthorities()))
                    .setSubject(user.getUsername())
                    .setIssuedAt(new Date())
                    .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                    .signWith(SignatureAlgorithm.HS512, SALT)
                    .compact();
        } catch (JsonProcessingException e) {
            throw new RuntimeException("生成Token异常！");
        }
    }


    /**
     * 解析Token
     * @param token
     * @return
     */
    public static Claims parseToken(String token){
        return Jwts.parser()
                .setSigningKey(SALT)
                .parseClaimsJws(token)
                .getBody();
    }

}